package edu.sju.ssm.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import edu.sju.ssm.entity.Publisher;

@Service
public class PublisherServiceImpl implements PublisherService {
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Transactional(readOnly = true)
	@Override
	public int getPublisherCount() {
		return jdbcTemplate.queryForObject("select count(*) from publishers", Integer.class);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	@Override
	public void addNewPublisher(Publisher publisher) {
		jdbcTemplate.update("insert into publishers(name, year_created, intro) values (?, ?, ?)", 
				publisher.getName(), publisher.getYearCreated(), publisher.getIntro());
	}

	@Transactional(readOnly = true)
	@Override
	public List<Publisher> getAllPublishers() {
		List<Publisher> result = jdbcTemplate.query("select id, name, year_created, intro from publishers", 
				this::mapRow);
		return result;
	}
	
	private Publisher mapRow(ResultSet rs, int rowNum) throws SQLException {
		return new Publisher(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4));
	}

}
